package springmvc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import springmvc.bean.Homework;
import springmvc.bean.Student;
import springmvc.bean.Student_homework;
import springmvc.dao.StudentHomeworkJdbc;
import springmvc.service.DbService;
import springmvc.service.impl.DbServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.ref.PhantomReference;
import java.util.List;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");

    @RequestMapping("/teacher_index")
    public String teacher_index(){
        return "teacher_index";
    }

    @RequestMapping("/teacher_add_homework")
    public String teacher_add_homework(HttpServletRequest req, HttpServletResponse resp){
        DbServiceImpl dbService = (DbServiceImpl) ac.getBean("DbServiceImpl");
        if("get".equalsIgnoreCase(req.getMethod())){
            return "teacher_add_homework";
        }else{
            List<Homework> homeworkList = dbService.get_all_homework();
            String homework_title = req.getParameter("title");
            int id = homeworkList.size()+1;
            String homework_id = id+"";
            dbService.add_homework(homework_title, homework_id);
            return "teacher_index";
        }
    }

    @RequestMapping("/teacher_add_student")
    public String teacher_add_student(HttpServletRequest req, HttpServletResponse resp){
        DbServiceImpl dbService = (DbServiceImpl) ac.getBean("DbServiceImpl");
        if("get".equalsIgnoreCase(req.getMethod())){
            return "teacher_add_student";
        }else{
            List<Student> studentList = dbService.get_all_student();
            String stu_name = req.getParameter("name");
            String stu_age = req.getParameter("age");
            String stu_tel = req.getParameter("tel");
            int id = studentList.size()+1;
            String student_id = id+"";
            dbService.add_student(student_id, stu_name, stu_age, stu_tel);
            return "teacher_index";
        }
    }

    @RequestMapping("/teacher_check_homework")
    public String teacher_check_homework(HttpServletRequest req, HttpServletResponse resp){
        DbServiceImpl dbService = (DbServiceImpl) ac.getBean("DbServiceImpl");
        List<Student_homework> all_homework = dbService.select_all();
        req.setAttribute("homework_list", all_homework);
        return "teacher_check_homework";
    }
}
